package com.example.xuecheng.contentservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.xuecheng.contentservice.mapper.TeachplanMapper;
import com.example.xuecheng.contentservice.service.CourseTeachplanService;
import dto.SaveCourseTeachplanDto;
import dto.TeachplanDto;
import exception.XueChengException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import po.Teachplan;

import java.time.LocalDateTime;
import java.util.List;

/**
 *   课程计划管理接口实现类
 * @author xiehaidong
 */
@Service
public class CourseTeachplanServiceImpl  implements CourseTeachplanService {
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Override
    public void saveCourseTeachplan(SaveCourseTeachplanDto saveCourseTeachplanDto) {
        if(saveCourseTeachplanDto.getId()!=null){
            //更新课程计划
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveCourseTeachplanDto,teachplan);
//            teachplan.setChangeDate(LocalDateTime.now());
            int update = teachplanMapper.updateById(teachplan);
            if(update<1){
                throw new XueChengException(500,"更新课程计划失败");
            }
            return;
        }
        Teachplan teachplan = new Teachplan();
        BeanUtils.copyProperties(saveCourseTeachplanDto,teachplan);
        //状态正常
        teachplan.setStatus(1);
        int count=getCourseTeacherplan(saveCourseTeachplanDto.getCourseId(), saveCourseTeachplanDto.getParentid());
        teachplan.setOrderby(count+1);
        int insert = teachplanMapper.insert(teachplan);
        if(insert<1){
            throw new XueChengException(500,"新增课程计划失败");
        }
    }

    /**
     * 根据父节点id获取子节点数量
     * @param parentId 父节点id
     * @return
     */
    private  int getCourseTeacherplan(Long courseId,Long parentId){
        LambdaQueryWrapper<Teachplan> teachplanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanLambdaQueryWrapper.eq(Teachplan::getCourseId,courseId);
        teachplanLambdaQueryWrapper.eq(Teachplan::getParentid,parentId);
        List<Teachplan> teachplans = teachplanMapper.selectList(teachplanLambdaQueryWrapper);
        return teachplans.size();
    }

    @Override
    public List<TeachplanDto> getTeacherPlanNodes(Long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Override
    public void delectTeachplan(Long teachplanId) {

    }

    @Override
    public void moveTeachplan(String move, Long teachplanId) {

    }
}
